package org.goldfish.demo.apicall.analysis.code.select;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.stage.DirectoryChooser;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.goldfish.demo.apicall.analysis.code.upload.AnalysisController;
import org.springframework.stereotype.Component;

import javax.annotation.Nullable;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Component
public class ProjectSelectorController {

    @FXML
    private Label projectPathLabel;

    @FXML
    private Button selectPathButton;
    
    @FXML
    private Button analyzeProjectButton;

    private static final String CACHE_FILE = "project_cache.json";

    private final ObjectMapper mapper = new ObjectMapper();

    @Setter
    private Stage primaryStage;
    
    private AnalysisController analysisController;
    
    private List<String> selectedPaths = new ArrayList<>();

    @FXML
    private void initialize() {
        selectPathButton.setOnAction(e -> {
            log.info("选择路径按钮被点击");
            
            // 创建文件选择器
            FileChooser fileChooser = new FileChooser();
            fileChooser.setTitle("选择文件");
            
            // 创建目录选择器
            DirectoryChooser directoryChooser = new DirectoryChooser();
            directoryChooser.setTitle("选择项目文件夹");
            
            // 为了简单起见，我们继续使用目录选择器，但允许多选的概念
            File dir = directoryChooser.showDialog(primaryStage);
            if (dir != null) {
                String path = dir.getAbsolutePath();
                log.info("输入路径：{}", dir.getAbsolutePath());
                projectPathLabel.setText(path);
                
                // 清空之前的路径并添加新路径
                selectedPaths.clear();
                selectedPaths.add(path);
                
                saveCachedPath(path);
            }
        });
        
        // 如果分析按钮存在，则添加事件处理
        if (analyzeProjectButton != null) {
            analyzeProjectButton.setOnAction(e -> {
                if (analysisController != null) {
                    try {
                        analysisController.execute(getSelectedPaths());
                    } catch (IOException ex) {
                        log.error("分析项目时出错", ex);
                    }
                }
            });
        }

        loadCachedPath();
    }
    
    public void setAnalysisController(AnalysisController analysisController) {
        this.analysisController = analysisController;
    }

    private void loadCachedPath() {
        ProjectCache cache = loadCache();
        if (cache != null && cache.projectPath != null && !cache.projectPath.isBlank()) {
            projectPathLabel.setText(cache.projectPath);
            selectedPaths.clear();
            selectedPaths.add(cache.projectPath);
            log.info("加载缓存项目路径: {}", cache.projectPath);
        } else {
            log.error("缓存为空");
        }
    }

    @Nullable
    private ProjectCache loadCache() {
        File file = new File(CACHE_FILE);
        log.info("读取{}", CACHE_FILE);
        if (file.exists()) {
            try {
                return mapper.readValue(file, ProjectCache.class);
            } catch (IOException e) {
                log.error("读取缓存文件失败", e);
            }
        }
        return null;
    }

    private void saveCachedPath(String path) {
        try {
            mapper.writerWithDefaultPrettyPrinter().writeValue(new File(CACHE_FILE), new ProjectCache(path));
            log.info("缓存项目路径: {}", path);
        } catch (IOException e) {
            log.error("保存缓存文件失败", e);
        }
    }

    // 保留原有方法以保持向后兼容
    public String getSelectedPath() {
        return selectedPaths.isEmpty() ? "" : selectedPaths.get(0);
    }
    
    // 新增方法：获取所有选中的路径
    public List<String> getSelectedPaths() {
        return new ArrayList<>(selectedPaths);
    }

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    private static class ProjectCache {
        private String projectPath;
    }
}